package com.carrey.dongyoufa.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bawei.carrey_common.utils.RandomUtil;
import com.carrey.dongyoufa.entity.User;
import com.carrey.dongyoufa.service.UserService;
/**
 * 	登录模块功能开发
 * @author Carre
 *
 */
@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 注册页面入口
	 * 
	 * @return
	 */
	@RequestMapping("toRegister")
	public String toRegister(Model model) {
		model.addAttribute("user", new User());
		return "user/register";
	}

	// 登录页面入口
	@RequestMapping("toLogin")
	public String toLogin(Model model) {
		model.addAttribute("user", new User());
		return "user/login";
	}

	/**
	 * 校验用户是否已存在
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("checkUser")
	@ResponseBody
	public boolean checkUser(User user) {
		System.out.println(user);
		User dbUser = userService.getUser(user);
		System.out.println(dbUser);
		if (dbUser != null) {
			return true;
		}
		return false;
	}

	// 注册功能
	@RequestMapping("register")
	public String register(@Valid @ModelAttribute("user") User user, BindingResult result) {

		if (result.hasErrors()) {
			return "user/register";
		}

		userService.register(user);
		return "redirect:toLogin";
	}

	/**
	 * 	获取验证码
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("getVerify")
	public String getVerify(User user, HttpSession session, Model model) {
		String random = RandomUtil.nextString(4);
		System.out.println(random);
		if (!StringUtils.isEmpty(random)) {
			// session数据设置
			session.setAttribute("VERIFY", random);
			session.setMaxInactiveInterval(5 * 30);
			model.addAttribute("user", user);
			return "/user/register";
		}
		return null;
	}

	// 登录操作 
	@RequestMapping("login")
	@ResponseBody
	public boolean login(User user, HttpSession session) {
		User dbUser = userService.getUserByUserNameAndPassword(user);
		if (dbUser!=null) {
			session.setAttribute("LOGIN_USER", dbUser);
			return true;
		}
		
		return false;
	}
	
	
	// 注销
    @RequestMapping("logout")
    public String logout(HttpSession session) {
          // 清空session
          session.invalidate();
          return "redirect:/";
    }
}
